<?php
declare (strict_types = 1);

namespace app\service;

use app\dao\AdminDao;
use app\exception\ServiceException;
use app\utils\encryption;
use think\App;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;

class AdminService
{
    protected $adminDao;
    public function __construct()
    {
        $this->adminDao = new AdminDao();
    }
    public function setCache(){
        $information = $this->adminDao
            ->hiddenPassword()
            ->getAll();
        Cache::set('adminInformation',$information,3600);
        return $information;
    }
    public function deleteCache() {
        $result = Cache::get('adminInformation');
        if ($result != null) Cache::delete('adminInformation');
        return true;
    }
    public function getInformation(){
        $result = Cache::get('adminInformation');
        if ($result != null) return $result;
        return $this->setCache();
    }
    public function deleteAdmin($id){
        try{
            Db::startTrans();
            $result = $this->adminDao->delete($id);
            $this->deleteCache();
            Db::commit();
        } catch (\Exception $exception){
            Db::rollback();
        }
        $this->setCache();
        return $result;
    }

    public function craeteAdmin($username,$password,$email,$isAdmin){
        if ($this->adminDao->findByUsername($username)->getOne() != null) throw new ValidateException("该用户名已存在!");
        try {
            $result = $this->adminDao->create([
                'username' => $username,
                'password' => encryption::getPassword($password),
                'head_img' => env('DEFAULT.STUDENT_HEAD_IMG' , null),
                'email' => $email,
                'is_admin' => $isAdmin
            ]);
            $this->deleteCache();
        } catch (\Exception $exception) {
            throw new ServiceException('创建失败');
        }
        $this->setCache();
        return $result;
    }

    public function setAdmin($id,$username,$password,$email,$is_admin) {
        try {
            $result = $this->adminDao->edit($id,[
                'username' => $username,
                'password' => encryption::getPassword($password),
                'email' => $email,
                'is_admin' => $is_admin
            ]);
            $this->deleteCache();
        } catch (\Exception $exception) {
            throw new ServiceException('修改失败');
        }
        $this->setCache();
        return $result;
    }

}
